﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace AIC_CS
{
    public partial class BaoCaoKetCongTacChinhSachTrongTamCongTacChinhSach : MyFromBase
    {
        private int IDDonVi;
        private int IDTenBaoCao;
        private int IDKyBaoCao;
        private static int IDBaoCao;
        private static string FilePath = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDataToDropDownList(ddlKyBaoCao, "KyBaoCao");
                //BindDataToDropDownList(ddlTenBaoCao, "PhuLucBaoCaoCT_CS");
                ddlKyBaoCao.Items.Insert(0, new ListItem("Chọn kỳ báo cáo", "-1"));
                //ddlTenBaoCao.Items.Insert(0, new ListItem("Chọn phụ lục", "-1"));
                lblDonVi.Text = MyCommon.GetTenDonVi(Session["userid"].ToString());
                
            }

        }
        protected void btnXemCiTiet_Click(object sender, EventArgs e)
        {
            #region Validate

            string sError = "";
            if (ddlKyBaoCao.SelectedIndex<=0)
                sError += "Bạn phải chọn kỳ báo cáo; ";
            if (txtbaocaoso.Text.Trim() == "")
                sError += "Bạn phải nhập số của báo cáo; ";

            if (txtDenNgay.Text.Trim()=="")
                sError += "Bạn phải chọn ngày báo cáo; ";

            if (sError != "")
            {
                MyCommon.AddMessage(this.Master, sError, MyConst.MessageType.Error);
                return;
            }
            #endregion Validate
            string sSQL = "";

            string temFilePath = UploadFile();
            if (temFilePath != "")
                FilePath = temFilePath;
            //UploadFile();
            #region param
            int id_donvi =Convert.ToInt32( MyCommon.GetDonViID(Session["userid"].ToString()));
            List<SqlParameter> lstParameter = new List<SqlParameter>();

            lstParameter.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, ddlKyBaoCao.SelectedValue));
            lstParameter.Add(SqlHelper.CreateParameterObject("@DonVi_ID", SqlDbType.Int, ParameterDirection.Input,id_donvi));
            lstParameter.Add(SqlHelper.CreateParameterObject("@BaoCaoSo", SqlDbType.NVarChar, ParameterDirection.Input, txtbaocaoso.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, "Cập nhật báo cáo kết quả công tác chính sách, trọng tâm công tác chính sách "));
            lstParameter.Add(SqlHelper.CreateParameterObject("@NoiDung", SqlDbType.NVarChar, ParameterDirection.Input, txtNoiDung.Value));
            lstParameter.Add(SqlHelper.CreateParameterObject("@FileDinhKem", SqlDbType.NVarChar, ParameterDirection.Input, FilePath));
            lstParameter.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(Session["userid"])));
            #endregion param
            
            sSQL = "INSERT INTO dbo.tblBaoCaoKetQuaCongTacChinhSachTrongTamCongTacChinhSach( KyBaoCaoID_DM ,DonVi_ID ,BaoCaoSo ,TenBaoCao ,NoiDung ,FileDinhKem ,CreateDate ,UpdateDate ,UserID) " +
                             "VALUES  ( @KyBaoCaoID_DM ,@DonVi_ID ,@BaoCaoSo ,@TenBaoCao ,@NoiDung ,@FileDinhKem ,GETDATE() ,GETDATE() ,@UserID )";
            SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);
            MyReportNumber = txtbaocaoso.Text.Trim();
            MyReportPeriod = ddlKyBaoCao.SelectedValue;
            MySwitchCase = "Null";
            //MyMasterPage = this.Master;
            Response.Redirect("PhuLuc_Update.aspx");
        }

        private string UploadFile()
        {
            try
            {
                if (fulFileDinhKem.HasFile)
                {
                    if (fulFileDinhKem.PostedFile.ContentLength < 2100000)
                    {
                        string sFolderPath = Server.MapPath(@"userfiles/BaoCao");
                        HttpPostedFile myFile = fulFileDinhKem.PostedFile;
                        string sFileName = myFile.FileName;
                        string[] arrFileName = sFileName.Split('.');
                        arrFileName[0] = DateTime.Now.ToString("ddMMyyhhssmm");
                        sFileName = arrFileName[0] + "." + arrFileName[1];
                        myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                        return "userfiles/BaoCao/" + sFileName;
                    }
                    else
                    {
                        return "";
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("index.aspx");
        }
      
        protected void BindDataToDropDownList(DropDownList BindDropDown, string MaDM)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@MaDM", SqlDbType.NVarChar, ParameterDirection.Input, MaDM));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblDanhMuc WHERE MaDM=@MaDM", arrParams);
            BindDropDown.DataSource = dt;
            BindDropDown.DataTextField = "TenDM";
            BindDropDown.DataValueField = "ID";
            BindDropDown.DataBind();
        }

        protected void ddlKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
         //   IDDonVi = Convert.ToInt32(MyCommon.GetDonViID(Session["userid"].ToString()));
         ////   IDTenBaoCao = Convert.ToInt32(ddlTenBaoCao.SelectedValue);
         //   IDKyBaoCao = Convert.ToInt32(ddlKyBaoCao.SelectedValue);
         //   DataTable dt = KiemTraBaoCaoTrungNhau(IDDonVi, IDKyBaoCao, IDTenBaoCao);
         //   if (dt.Rows.Count != 0)
         //   {
         //       FilePath = dt.Rows[0][6].ToString();
         //       //txtTenBaoCao.Text = dt.Rows[0]["TenBaoCao"].ToString();
         //       txtNoiDung.Value = dt.Rows[0]["NoiDung"].ToString();
         //       IDBaoCao = Convert.ToInt32(dt.Rows[0]["ID"]);
         //       btnXemCiTiet.CommandArgument = MyConst.Action.Update;
         //       lbtFileDinhkem.Text = dt.Rows[0][6].ToString().Split('/')[2];
         //   }
         //   else
         //   {
         //       btnXemCiTiet.CommandArgument = MyConst.Action.Addnew;
         //   }
        }

        protected void ddlTenBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        protected DataTable KiemTraBaoCaoTrungNhau(int IDDonVi, int KyBaoCao, int IDBaoCao)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@TenBaoCaoID", SqlDbType.Int, ParameterDirection.Input, IDBaoCao));
            arrParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, KyBaoCao));
            arrParams.Add(SqlHelper.CreateParameterObject("@DonVi_ID", SqlDbType.Int, ParameterDirection.Input, IDDonVi));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblBaoCaoAttach WHERE BaoCaoAttachID_DM = @TenBaoCaoID AND KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonVi_ID = @DonVi_ID", arrParams);
            return dt;
        }

        protected void lbtFileDinhkem_Click(object sender, EventArgs e)
        {
            if (FilePath.Trim().Length != 0)
            {
                string FileName = FilePath.Split('/')[2];
                Download(FileName, FilePath);
            }
        }

        public static void Download(string sFileName, string sFilePath)
        {
            HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
            String Header = "Attachment; Filename=" + sFileName;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
            System.IO.FileInfo Dfile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
            HttpContext.Current.Response.WriteFile(Dfile.FullName);
            HttpContext.Current.Response.End();
        }
      
    }
}
